package ferp.android.views.table.controller;

import android.graphics.Point;
import android.graphics.Rect;
import ferp.android.views.CardView;
import ferp.android.views.table.TableView;
import ferp.android.views.table.animation.MovingCard;

/**
* User: olegs
* Date: 05/01/2015 11:58
*/
public class CardDragController extends MovingController
{
  public CardDragController(TableView.Listener listener, TableView table, MovingCard mc, Rect sink)
  {
    super(listener, table, mc, sink);
  }

  @Override
  public void select(int player, CardView cv)
  {
    mark(cv, Mark.HIDE);
    selected[player] = cv;
  }

  @Override
  public void deselect(int player, CardView cv)
  {
    selected[player] = null;
    mark(cv, Mark.SHOW);
  }

  @Override
  public void onMovingStarted(int player, CardView cv, Point touch)
  {
    if (state == State.NONE)
    {
      // move controller to 'ANIMATION' state to prevent offer dialog appearance and as consequence double processing
      state = State.ANIMATION;

      // disable all candidates except the one that is moving to prevent moving few of them in the same time
      table.enablePlayerCards(player, false);
      cv.setEnabled(true);

      // make the card view be selected
      select(player, cv);

      // initialize moving card state
      mc.initialize(cv, touch);
    }
  }

  @Override
  public void onMoving(CardView cv, int x, int y)
  {
    if (state == State.ANIMATION)
      mc.move(x, y);
  }

  @Override
  public void onMovingEnded(CardView cv)
  {
    if (state == State.ANIMATION)
    {
      //Log.log.debug(Log.TAG, "moving ended for " + cv.card() + ", enabled: " + cv.isEnabled());

      // the card can be released only if its center is inside the sink area
      if (sink.contains(cv.getLeft() + cv.getWidth() / 2, cv.getTop() + cv.getHeight() / 2))
        listener.onCardReleased(cv.card());
      else
        mc.rollback();
    }
  }
}
